/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans.dao;

import core.APersistenceManager;
import core.IGameDAO;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
import persistence.*;
import validators.GameValidator;

/**
 *
 * @author Ivan
 */
public class GameDAO extends APersistenceManager<Game> implements IGameDAO {

    public GameDAO() {
        super(Game.class, new GameValidator());
    }

    @Override
    public Set<Game> getGamesByOwner(int idUser) {
        SysUser owner = getEntityManager().find(SysUser.class, BigDecimal.valueOf(idUser));
        return owner.getGameSet();
    }

    @Override
    public Set<Game> getGamesByPlayer(int idPlayer) {
        Player player = getEntityManager().find(Player.class, BigDecimal.valueOf(idPlayer));
        return player.getGameSet();
    }

    @Override
    public Set<Game> getGamesByTeam(int idTeam) {
        Set<Game> games = new HashSet<Game>();
        Team team = getEntityManager().find(Team.class, BigDecimal.valueOf(idTeam));

        for (GameContract gc : team.getGameContractSet()) {
            if (team.equals(gc.getTeamId())) {
                games.add(gc.getGameId());
            }
        }
        return games;
    }

    @Override
    public Set<Game> getGamesByLeague(int idLeague) {

        League l = getEntityManager().find(League.class, BigDecimal.valueOf(idLeague));
        Set<Game> res = new HashSet<Game>();
        Set<Tournament> trs = l.getTournamentSet();
        for (Tournament t : trs) {

            Set<Game> gs = t.getGameSet();
            for (Game g : gs) {
                res.add(g);
            }
        }

        return res;

    }

    @Override
    public Set<Game> getGamesByTournament(int idTournament) {
        Tournament tournament = getEntityManager().find(Tournament.class, BigDecimal.valueOf(idTournament));
        return tournament.getGameSet();
    }

    @Override
    public Team getWinner(int id) {
        Game game = getEntityManager().find(Game.class, BigDecimal.valueOf(id));
        return game.getWinnerTeamId();
    }
}
